package vcsn.entities;

import java.util.Arrays;
import java.util.HashMap;

import vcsn.Config;

@SuppressWarnings("serial")
public class LastAppliedCommitHashList extends HashMap<String, String> {

	public void setCommitHash(String pUnit, String pValue){
		this.put(pUnit, pValue);
	}
	
	public String[] getOrderedIDs(){
		String[] lResult = new String[this.size()];

		lResult = this.keySet().toArray(lResult);

		Arrays.sort(lResult);

		return lResult;
	}
	
	public String[] getOrderedValues(){
		String[] lResult = new String[this.size()];
		String[] lKeySet  = this.getOrderedIDs();

		int i = 0;
		for (String lKey : lKeySet){
			lResult[i] = this.get(lKey);
			i++;
		}

		return lResult;
	}
	
	public String get(Object key){
		String lResult = super.get(key);

		return lResult;
	}

	@Override
	public LastAppliedCommitHashList clone(){
		return (LastAppliedCommitHashList) super.clone();
	}
	
	public String toString(){
		String[] lIDs		= this.getOrderedIDs();
		String[] lRequests = this.getOrderedValues();

		String lText = Config.setOpen;

		for (int i = 0; i < lRequests.length; i++){
			lText += lIDs[i];
			lText += Config.equal;
			lText += lRequests[i].toString();

			if (i + 1 < lRequests.length){
				lText += Config.separator;
			}
		}

		lText += Config.setClose;

		return lText;
	}
	
	public static LastAppliedCommitHashList toLastAppliedCommitHashList(String pString){
		LastAppliedCommitHashList lcommitHash = new LastAppliedCommitHashList();
		String[] lTexts = pString.replace(Config.setOpen, "").replace(Config.setClose, "").split(Config.separator);
		
		for(String str : lTexts){
			lcommitHash.setCommitHash(str.split(Config.equal)[0], str.split(Config.equal)[1]);
		}
		return lcommitHash;
	}
}
